<?php 
define ('KODOWANIE', 'UTF-8');

class Parser
{ 
   private static $jezyk;
   private static $slownik;
   private $error;
   private static $instance; 
   private $plik;
   public static $textArray = array();
   
   public function __construct($jezyk) {

      if(!isset(self::$instance)){
         $module = Zend_Controller_Front::getInstance()->getRequest()->getParam('module');
         self::$jezyk = $jezyk;
         $this->plik = APPLICATION_PATH . '/../resources/languages/' . self::$jezyk . '/' . $module . '.ini';

         self::$textArray = $src;
         $this->load();  
         self::$instance = $this;
      } 
      
      return self::$instance;
   }

    private function load() {

      if(!file_exists($this->plik)) {
         print_r('Cannot find ' . $this->plik);
         return false;
      }
      if(!($fp = fopen($this->plik, 'rb'))) {
         print_r('Cannot open ' . $this->plik);
         return false;
      }
      self::$slownik = @ fread($fp, filesize($this->plik));

      fclose ($fp);
   }
  
   public function txt($tekst, $arg1 = '', $arg2 = '', $arg3 = '') {   
         $tekst_szuk = $tekst.'=';
         $tok = strtok(self::$slownik, "\n\t");
         
         while($tok && !strstr($tok, $tekst_szuk)) {
            $tok = strtok("\n\t");
         }
         
         if($tok) {
            $wynik = strstr($tok, '=');
            $wynik = $this->UTF8_substr($wynik, 1, $this->UTF8_strlen($wynik)-2);
            $wynik = str_replace('[arg2]', $arg2, str_replace('[arg1]', $arg1, $wynik));
            $wynik = str_replace('[arg3]', $arg3, $wynik);
         }
         else {
            $wynik = 'BRAK TEKSTU';
         }
         
         return $wynik;
   }
   
   private function UTF8_strlen($str) {
      if(KODOWANIE == 'UTF-8')
         return(strlen($str));
      else
         return(strlen($str));
   }

    private function UTF8_substr($str, $start, $length = null) {
      if(KODOWANIE == 'UTF-8') {
         if(isset($length))
            return(substr($str, $start, $length));
         else
            return(substr($str, $start));
      }
      else {
         if(isset($length))
            return(substr($str, $start, $length));
         else
            return(substr($str, $start));
      }
   }

   private function UTF8_strtolower($str) {
      if(KODOWANIE == 'UTF-8') {
         if(!defined('UTF8_NOMBSTRING') && function_exists('mb_strtolower'))
            return strtolower($str, 'utf-8');
            
         global $UTF8_UPPER_TO_LOWER;
         $uni = utf8_to_unicode($str); 
         
         for ($i = 0; $i < count($uni); $i++){
            if($UTF8_UPPER_TO_LOWER[$uni[$i]]){
               $uni[$i] = $UTF8_UPPER_TO_LOWER[$uni[$i]];
            }
         }
         return unicode_to_utf8($uni);
      }
      else
         return(strlen($str));
   }
}

